/**
 * 
 */
package com.cipe.cmrs.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cipe.cmrs.bean.CodeDescriptionBean;
import com.cipe.cmrs.exception.QueryException;
import com.cipe.cmrs.model.AccountCode;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.util.DateUtil;

/**
 * @author Incepio
 * 
 */
@Service
@Transactional
public class AccountCodeService extends BaseService<AccountCode> {

	@Autowired
	private UserService	userService;
	@Autowired
	private ConversionService conversionService;

	public AccountCode saveAccountCode(AccountCode accountCode, Integer userId) {
		if (accountCode != null) {
			User user = userService.findById(userId);
			AccountCode dbAccountCode = findById(accountCode.getId());
			if (dbAccountCode == null) {
				dbAccountCode = new AccountCode();
				dbAccountCode.setCreatedBy(user);
				dbAccountCode.setCreationDate(DateUtil.getCurrentDate());
			}
			dbAccountCode.setAccountCode(accountCode.getAccountCode());
			dbAccountCode.setDescription(accountCode.getDescription());
			dbAccountCode.setUpdatedBy(user);
			dbAccountCode.setUpdationDate(DateUtil.getCurrentDate());
			return merge(dbAccountCode);
		}
		return null;
	}

	@Transactional(readOnly = true)
	public List<CodeDescriptionBean> getAllAccountCodeBeans(List<String> columns) {
		List<CodeDescriptionBean> results = new ArrayList<CodeDescriptionBean>();
		StringBuilder queryString = new StringBuilder("SELECT ");
		if (columns != null && columns.size() > 0) {
			int i = 0;
			for (; i < columns.size() - 1; i++) {
				queryString.append("obj." + columns.get(i) + ", ");
			}
			queryString.append("obj." + columns.get(i));
		} else {
			queryString.append("obj");
		}
		queryString.append(" FROM ");
		queryString.append(AccountCode.class.getName());
		queryString.append(" obj ");
		queryString.append(" ORDER BY obj.accountCode ASC ");
		try {
            List<AccountCode> list = dao.getResultList(queryString.toString(), AccountCode.class, columns.toArray(new String[0]), null);
			if (list != null) {
				for (AccountCode code : list) {
					results.add(conversionService.convert(code, CodeDescriptionBean.class));
				}
			}
		} catch (QueryException e) {
			// XXX: User should be notified by this.
			logger.error("Exception encountered while fetching Accountcode from db.", e);
		}
		return results;
	}
}
